package com.message.tcp.ip.ui.member.action;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.message.tcp.ip.socket.configure.entity.Member;
import com.message.tcp.ip.socket.configure.service.MemberService;
import com.message.tcp.ip.ui.member.dialog.MemberAddDialog;
import com.message.tcp.ip.ui.member.dialog.MemberTable;

public class MemberAddAction implements ActionListener {
	private JTextField memIdText;
	private JTextField iinText;
	private JTextField nameText;
	private JTextField locationText;
	private MemberTable table;
	private MemberService memberService;
	private MemberAddDialog dialog;
	public MemberAddAction(JTextField memIdText, JTextField iinText,
			JTextField nameText, JTextField locationText, MemberTable table, MemberAddDialog dialog) {
		this.memIdText = memIdText;
		this.iinText = iinText;
		this.nameText = nameText;
		this.locationText = locationText;
		this.table = table;
		this.dialog = dialog;
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
		memberService = (MemberService) context.getBean("memberService");
	}
	@Override
	public void actionPerformed(ActionEvent event) {
		String memId = memIdText.getText();
		String iin = iinText.getText();
		String name = nameText.getText();
		String location = locationText.getText();
		
		Member member = new Member();
		member.setIin(iin);
		member.setMemId(memId);
		member.setName(name);
		member.setLocation(location);
		Member mem = memberService.getMemberFromIIN(iin);
		if(mem == null){
			memberService.save(member);
			memIdText.setEditable(false);
			iinText.setEditable(false);
			nameText.setEditable(false);
			locationText.setEditable(false);
			dialog.dispose();
			JOptionPane.showMessageDialog(null, "Success !");
			Member memb = memberService.getMemberFromIIN(iin);
			DefaultTableModel model = (DefaultTableModel) table.getModel();
			model.addRow(new Object[]{memb.getId(),memb.getIin(),memb.getMemId(),memb.getName(),memb.getLocation()});
		}
		else{
			JOptionPane.showMessageDialog(null, "Duplicate IIN", "Error Dialog", JOptionPane.ERROR_MESSAGE);
		}
		
	}

}
